package com.winhxd.b2c.order.api;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.context.CustomerUser;
import com.winhxd.b2c.common.context.UserContext;
import com.winhxd.b2c.common.domain.PagedList;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.common.ApiCondition;
import com.winhxd.b2c.common.domain.order.condition.*;
import com.winhxd.b2c.common.domain.order.enums.*;
import com.winhxd.b2c.common.domain.order.model.OrderAfterSaleDetail;
import com.winhxd.b2c.common.domain.order.model.OrderExpressInfo;
import com.winhxd.b2c.common.domain.order.vo.*;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.order.service.OrderAfterSaleDetailService;
import com.winhxd.b2c.order.service.OrderAfterSaleService;
import com.winhxd.b2c.order.service.OrderExpressService;
import com.winhxd.b2c.order.service.OrderQueryService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author:zhangyanwei
 * @date:2019/1/7 16:19:38
 * @Description:订单售后服务接口(APP调用)
 **/
@RestController
@Api(tags = "ApiOrderAfterSale")
@RequestMapping(value = "/api-order/afterSale")
public class ApiOrderAfterSaleController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApiOrderAfterSaleController.class);

    @Autowired
    private OrderExpressService expressService;

    @Autowired
    private OrderAfterSaleDetailService afterSaleDetailService;

    @Autowired
    private OrderAfterSaleService orderAfterSaleService;

    @Autowired
    private OrderQueryService orderQueryService;

    @ApiOperation(value = "获取订单售后详情", notes = "获取订单售后详情")
    @ApiResponses({@ApiResponse(code = BusinessCode.CODE_OK, message = "操作成功")})
    @RequestMapping(value = "/4501/v1/getOrderAfterSaleInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<OrderInfoAfterSaleVO> getOrderAfterSaleInfo(@RequestBody OrderQueryCondition condition) {
        String logTitle = "/api-order/afterSale/4501/v1/getOrderAfterSaleInfo-获取订单售后信息";
        this.validateCustomerId(condition);
        ResponseResult<OrderInfoAfterSaleVO> result = new ResponseResult<>();
        condition.setFlag(CommonStatusEnum.YES.getTypeCode());
        OrderInfoAfterSaleVO ov = afterSaleDetailService.getAfterSaleInfo(condition);
        result.setData(ov);
        LOGGER.info("{}=--结束--", logTitle);
        return result;
    }

    @ApiOperation(value = "售后信息列表", notes = "售后信息列表")
    @ApiResponses({@ApiResponse(code = BusinessCode.CODE_OK, message = "操作成功"),
            @ApiResponse(code = BusinessCode.CODE_1001, message = "服务器内部异常")
    })
    @RequestMapping(value = "/4505/v1/findOrderAfterSaleList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<PagedList<OrderInfoAfterSaleVO>> findOrderAfterSaleList(@RequestBody OrderQueryCondition condition) {
        String logTitle = "/api-order/afterSale/4505/v1/findOrderAfterSaleList-售后列表";
        LOGGER.info("{}=--开始--{}", logTitle, JsonUtil.toJSONString(condition));
        this.validateCustomerId(condition);
        ResponseResult<PagedList<OrderInfoAfterSaleVO>> result = new ResponseResult<>();
        PagedList<OrderInfoAfterSaleVO> plist = afterSaleDetailService.selectAfterSaleInfo(condition);
        result.setData(plist);
        LOGGER.info("{}=--结束--", logTitle);
        return result;
    }

    private void dealPlist(PagedList<OrderInfoVO> plist){
        if(null == plist ||  null == plist.getData()) {
            return;
        }
        for (OrderInfoVO ov: plist.getData()) {
            this.dealOrderInfoVO(ov);
        }
    }

    private void dealOrderInfoVO(OrderInfoVO ov){
        if(null == ov){
            return;
        }
        List<OrderDetailVO> ovlist = ov.getOrderDetailVOList();
        if(null == ovlist){
            return ;
        }
        Iterator it = ovlist.iterator();
        while (it.hasNext()){
            OrderDetailVO odv = (OrderDetailVO)it.next();
            if(null == odv.getOrderAfterSale()){
                it.remove();
            }
        }
    }

    @ApiOperation(value = "订单售后申请", notes = "订单售后申请")
    @ApiResponses({
            @ApiResponse(code = BusinessCode.CODE_440601, message = "订单已自动确认收货，不能再进行任何操作"),
            @ApiResponse(code = BusinessCode.CODE_440607, message = "订单发发起过【未发货退款】售后,且已审核通过,不能重复发起售后"),
            @ApiResponse(code = BusinessCode.CODE_440602, message = "不能重复发起售后"),
            @ApiResponse(code = BusinessCode.CODE_OK, message = "操作成功")})
    @RequestMapping(value = "/4502/v1/afterSaleApply", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Void> afterSaleApply(@RequestBody OrderAfterSaleApplyCondition condition) {
        String logTitle = "/api-order/afterSale/4502/v1/afterSaleApply-订单售后申请";
        LOGGER.info("{}=--开始--{}", logTitle, JsonUtil.toJSONString(condition));
        this.validateCustomerId(condition);
        ResponseResult<Void> result = new ResponseResult<>();
        //待发货退款skuId和orderDetailId为空
        if(condition.getAfterSaleType().intValue() == OrderAfterSaleTypeEnum.WAIT_DELIVERING_REFUND.getTypeCode().intValue()){
            condition.setSkuId(null);
            condition.setOrderDetailId(null);
        }
        afterSaleDetailService.saveOrderAfterSale(condition);
        return result;
    }

    @ApiOperation(value = "订单售后申请撤销", notes = "订单售后申请撤销")
    @ApiResponses({
            @ApiResponse(code = BusinessCode.CODE_440605, message = "售后已审核，不能撤销"),
            @ApiResponse(code = BusinessCode.CODE_OK, message = "操作成功")})
    @RequestMapping(value = "/4503/v1/afterSaleApplyCancel", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Void> afterSaleApplyCancel(@RequestBody OrderAfterSaleApplyCancelCondition condition) {
        String logTitle = "/api-order/afterSale/4503/v1/afterSaleApplyCancel-订单售后申请撤销";
        LOGGER.info("{}=--开始--{}", logTitle, JsonUtil.toJSONString(condition));
        this.validateCustomerId(condition);
        ResponseResult<Void> result = new ResponseResult<>();
        OrderAfterSaleDetail afterSaleDetail = new OrderAfterSaleDetail();
        this.dealOrderAfterSaleDetail(condition,afterSaleDetail);
        afterSaleDetailService.cancelOrderAfterSaleApply(afterSaleDetail);
        return result;
    }

    private void dealOrderAfterSaleDetail(OrderAfterSaleApplyCancelCondition condition,OrderAfterSaleDetail afterSaleDetail){
        afterSaleDetail.setId(condition.getId());
        afterSaleDetail.setResultStatus(AfterSaleAuditStatusEnum.CANCEL.getTypeCode());
        afterSaleDetail.setCompleteStatus(CommonStatusEnum.YES.getTypeCode());
        afterSaleDetail.setViewStatus(AfterSaleViewStatusEnum.CANCLED.getTypeCode());
        Date now = new Date();
        afterSaleDetail.setCancelTime(now);
        afterSaleDetail.setCompleteTime(now);
        afterSaleDetail.setUpdated(now);
        afterSaleDetail.setUpdatedBy(String.valueOf(condition.getCustomerId()));
    }

    @ApiOperation(value = "新增物流信息(手机端发起 退货发货、换货发货)", notes = "新增物流信息(手机端发起 退货发货、换货发货)")
    @ApiResponses({
            @ApiResponse(code = BusinessCode.CODE_440608, message = "售后状态错误,不能输入物流信息"),
            @ApiResponse(code = BusinessCode.CODE_440609, message = "不能重复输入物流信息"),
            @ApiResponse(code = BusinessCode.CODE_440604, message = "会员超时未填写快递信息，售后订单自动关闭"),
            @ApiResponse(code = BusinessCode.CODE_OK, message = "操作成功")})
    @RequestMapping(value = "/4504/v1/saveExpressInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult<Void> saveExpressInfo(@RequestBody OrderExpressCondition condition) {
        String logTitle = "/api-order/afterSale/4504/v1/saveExpressInfo-新增物流信息(手机端发起 退货发货、换货发货)";
        LOGGER.info("{}=--开始--{}", logTitle, JsonUtil.toJSONString(condition));
        this.validateCustomerId(condition);
        this.validateExpressCondition(condition);
        ResponseResult<Void> result = new ResponseResult<>();
        OrderExpressInfo expressInfo = new OrderExpressInfo();
        this.setExpressProperty(condition,expressInfo);
        expressService.saveExpressForReturning(expressInfo);
        return result;
    }

    private void validateExpressCondition(OrderExpressCondition condition){
        if(!StringUtils.isBlank(condition.getExpressCompanyNo()) && StringUtils.isBlank(condition.getExpressNo())){
            LOGGER.error("选择快递公司时必须输入快递单号!!");
            throw new BusinessException(BusinessCode.CODE_440610);
        }
    }

    private void setExpressProperty(OrderExpressCondition condition,OrderExpressInfo expressInfo){
        Date now = new Date();
        BeanUtils.copyProperties(condition,expressInfo);
        expressInfo.setCreated(now);
        expressInfo.setSendUser(String.valueOf(condition.getCustomerId()));
        expressInfo.setSendTime(now);
        expressInfo.setCreatedBy(String.valueOf(condition.getCustomerId()));
        expressInfo.setUpdated(now);
        expressInfo.setUpdatedBy(String.valueOf(condition.getCustomerId()));
    }

    private void validateCustomerId(ApiCondition condition){
        if(null == condition.getCustomerId()){
            LOGGER.error("用户为空!!");
            throw new BusinessException(BusinessCode.CODE_440101);
        }
    }

}
